//
//  AlbumStorage.m
//  us
//
//  Created by karry on 2025/4/17.
//

#import "AlbumStorage.h"
#import "USCoreDataStack.h"
#import "MJExtension/MJExtension.h"


@implementation AlbumStorage

+ (instancetype)shared {
    static AlbumStorage *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [AlbumStorage new];
    });
    return instance;
}

- (NSArray<Album *> *)fetchLocalAlbums {
    
    return [Album jk_all:[NSPredicate predicateWithValue:YES] sortDescriptors: @[
        [NSSortDescriptor sortDescriptorWithKey:@"topFlag" ascending:NO],
        [NSSortDescriptor sortDescriptorWithKey:@"topUpdateAt" ascending:NO]
        ]inContext:USCoreDataStack.shared.context];
    
}

- (NSArray *)syncRemoteAlbums:(NSArray<NSDictionary *> *)jsonArray {
    
    if (![jsonArray isKindOfClass:[NSArray class]]) {
        return nil;
    }
    
    NSManagedObjectContext *context = [USCoreDataStack shared].context;
    // 清空所有 Album
    NSFetchRequest *request = [Album fetchRequest];
    NSArray *existing = [context executeFetchRequest:request error:nil];
    for (NSManagedObject *obj in existing) {
        [context deleteObject:obj];
    }

    NSMutableArray *list = [NSMutableArray array];
    for (NSDictionary *dict in jsonArray) {
        Album *album = [NSEntityDescription insertNewObjectForEntityForName:@"Album" inManagedObjectContext:context];
        [album mj_setKeyValues:dict];
        [list addObject:album];
    }
    
    [[USCoreDataStack shared] save];
    
    return list;
    
}

@end
